<?php
/**
 * Created by PhpStorm.
 * User: dy
 * Date: 2019/12/26
 * Time: 15:51
 */
namespace app\admin\validate;
use app\admin\enum\AdminMenuEnum;
use app\admin\model\AdminMenu;
use app\common\validate\BaseValidate;
use util\StringUtil;

class AdminMenuValidate extends BaseValidate
{
    public function __construct()
    {
        parent::__construct();
        $this->rule['is_hide|是否隐藏'] .=  AdminMenuEnum::getEnumIdsToStr('is_hide');
    }
    protected $rule = [
        'id'=>'require|number',
        'name|菜单名称'=>'require',
        'url'=>'check_url:',
        'parent_id|父菜单'=>'number',
        'is_hide|是否隐藏'=>'number|in:',
        'sort|排序'=>'number',
    ];
    protected $scene = [
        'edit'=>['id','name','url','parent_id','is_hide','sort'],
        'add'=>['name','url','parent_id','is_hide','sort']
    ];

    protected function check_url($value,$rule,$data){
        if(strpos($value,'http') === 0){
            return true;
        }
        if(empty($value)){
            return true;
        }
        if(count(StringUtil::instance()->strToArr($value,'/')) != 3){
            return 'url格式错误';
        }
        if(!isset($data['id']) || empty($data['id'])) {
            $menu_id = AdminMenu::instance()->where('url', parse_name($value))->value('id');
            if ($menu_id) {
                return '此菜单url已存在';
            }
        }
        return true;
    }
}